package com.axend.aerosense.user.fragment;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;

import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.utils.EquipmentUtil;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.ui.CustomUpdateDialog;
import com.axend.aerosense.common.ui.WebActivity;
import com.axend.aerosense.common.util.CheckUpdateUtil;
import com.axend.aerosense.user.BuildConfig;
import com.axend.aerosense.user.R;
import com.axend.aerosense.user.UserSettingActivity;
import com.axend.aerosense.user.databinding.UserAboutFragmentBinding;
import com.axend.aerosense.user.viewmodel.UserAboutViewModel;

import io.reactivex.disposables.Disposable;

public class UserAboutFragment extends MvvmBaseFragment<UserAboutFragmentBinding, UserAboutViewModel> {

    private Disposable disposable;
    private CustomUpdateDialog customUpdateDialog;

    public static UserAboutFragment getInstance(){
        UserAboutFragment fragment = new UserAboutFragment();
//        Bundle bundle = new Bundle();
//        bundle.putString(ARG_PARAM, str);
//        fragment.setArguments(bundle);   //设置参数
        return fragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    private void initView() {
//        viewDataBinding.userVersion.setText(EquipmentUtil.getAppVersionName());
        StringBuilder builder = new StringBuilder();
        builder.append(EquipmentUtil.getAppVersionName());
        if (isDebug()){
            builder.append("\nVersion Code: " + getVersionCode())
                    .append("\nBuild Time: " + BuildConfig.BUILD_TIME)
                    .append("\nApp Server: " + UrlApi.getBaseUrl())
                    .append("\nRadar Server: " + UrlApi.getRadarTcpServerUrl());
        }
        viewDataBinding.userVersion.setText(builder.toString());
        //检查更新
        viewDataBinding.userCheckVersion.setOnClickListener(v -> {
            if (disposable == null){
                CheckUpdateUtil checkUpdateUtil = new CheckUpdateUtil(getActivity(),false);
                checkUpdateUtil.checkUpdate();
//                checkUpdate();
            }
        });
        //去评分
        viewDataBinding.userGo.setOnClickListener(v -> {
            try{
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("market://details?id=com.axend.aerosense"));
                startActivity(intent);
            }catch (Exception e){

            }

        });
        //用户协议
        viewDataBinding.userAgreement.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), WebActivity.class);
            intent.putExtra(WebActivity.URL, UrlApi.userProtocolUrl);
            intent.putExtra(WebActivity.TITLE, getString(R.string.user_title_user_agreement));
            startActivity(intent);
        });
        //用户 隐私政策
        viewDataBinding.userPrivacy.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), WebActivity.class);
            intent.putExtra(WebActivity.URL, UrlApi.privacyProtocolUrl);
            intent.putExtra(WebActivity.TITLE, getString(R.string.user_title_user_privacy));
            startActivity(intent);
        });
    }

    private int getVersionCode(){
        try {
            return getContext().getPackageManager().getPackageInfo(getContext().getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private boolean isDebug(){
        boolean isDebug = getContext().getApplicationInfo()!=null&&
                (getContext().getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE)!=0;
        return isDebug;
    }

    //已抽离成工具类
//    public void checkUpdate(){
//        disposable = EasyHttp.post(UrlApi.URL.GetAppVersion.getUrl())
//                .cacheMode(CacheMode.NO_CACHE)
//                .upJson(JsonUtil.toJson(new BaseDevInfoBean()))
//                .execute(new SimpleCallBack<UpdateAppBean>() {
//                    @Override
//                    public void onTokenExpire() {
//                        disposable = null;
//                    }
//
//                    @Override
//                    public void onError(ApiException e) {
//                        e.printStackTrace();
//                        disposable = null;
//                    }
//
//                    @Override
//                    public void onSuccess(UpdateAppBean updateAppBean) {
//                        String versionCode = "" + EquipmentUtil.getAppVersionNumber();
//                        // 需要更新提示的 1. 客户端版本和服务器端不一致, 2.强制更新的, 3. 可跳过的版本号和已经跳过的版本号不一致
//                        if(!TextUtils.isEmpty(updateAppBean.getServiceEdtion()) && !versionCode.equals(updateAppBean.getServiceEdtion()) ){
//                            try {
//                                if (TextUtils.isEmpty(updateAppBean.getServiceEdtion())
//                                        || Integer.parseInt(versionCode) >= Integer.parseInt(updateAppBean.getServiceEdtion())){
//                                    disposable = null;
//                                    ToastUtils.showShort(R.string.common_new_version);
//                                    return;
//                                }
//                            }catch (Exception e){
//                                e.printStackTrace();
//                            }
//
//                            customUpdateDialog = new CustomUpdateDialog(getActivity(), updateAppBean, false);
//                            customUpdateDialog.setCancelable(false);
//                            customUpdateDialog.setCanceledOnTouchOutside(false);
//
//                            customUpdateDialog.setOnClickBottomListener(new CustomUpdateDialog.OnClickBottomListener() {
//                                @Override
//                                public void onPositiveClick() {
//
//                                }
//
//                                @Override
//                                public void onNegtiveClick() {
//                                    if(updateAppBean.getState() == 0){
//                                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.LAST_JUMP_VERSION, updateAppBean.getServiceEdtion());
//                                    }
//
//                                }
//
//                                @Override
//                                public void onCloseClick() {
//                                    if(updateAppBean.getState() == 0){
//                                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.LAST_JUMP_VERSION, updateAppBean.getServiceEdtion());
//                                    }
//                                }
//                            });
//                            customUpdateDialog.show();
//                            disposable = null;
//                        }
//                    }
//                });
//    }

    @Override
    public void onResume() {
        super.onResume();
        ((UserSettingActivity)getActivity()).setTitle(getString(R.string.user_about));
    }

    @Override
    public int getLayoutId() {
        return R.layout.user_about_fragment;
    }

    @Override
    public int getBindingVariable() {
        return 0;
    }

    @Override
    protected UserAboutViewModel getViewModel() {
        return new ViewModelProvider(this).get(UserAboutViewModel.class);
    }

    @Override
    protected void onRetryBtnClick() {

    }
}
